<template>
  <el-dropdown trigger="click" placement="bottom-end" @command="configLang">
    <el-button circle v-if="type === 'button'">
      <el-icon><niu-icon-locale /></el-icon>
    </el-button>
    <div class="localePicker_text" v-if="type === 'text'">
      <el-icon><niu-icon-locale /></el-icon>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="item in langList"
          :key="item.value"
          :command="item"
          :class="{ selected: lang == item.value }"
          >{{ item.name }}</el-dropdown-item
        >
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import sysCache from '@/utils/cache'
import projectSetting from '@/settings/projectSetting'
import { useI18n } from 'vue-i18n'

const langList = [
  {
    name: '简体中文',
    value: 'zh-CN'
  },
  {
    name: 'English',
    value: 'en-US'
  }
]
export default defineComponent({
  name: 'AppLocalePicker',
  props: {
    type: {
      type: String,
      default: 'button'
    }
  },
  setup() {
    const lang = ref(sysCache.localCache.getCache('APP_LANG') || projectSetting.LANG)

    const { locale } = useI18n()

    // 切换语言环境
    function configLang(e) {
      lang.value = e.value
      locale.value = e.value
      sysCache.localCache.setCache('APP_LANG', e.value)
      // 刷新当前页面
      location.reload()
    }

    return {
      langList,
      lang,
      configLang
    }
  }
})
</script>

<style lang="scss" scoped>
@import '../../../style/mixin.scss';

.selected {
  color: var(--el-color-primary);
}

.localePicker_text {
  height: 48px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 10px;

  &:hover {
    @include hover_bg_color();
  }
}
</style>
